<template>
  <div id="globalHeader">
    <a-row :wrap="false">
      <!-- 左侧 logo -->
      <a-col flex="200px">
        <RouterLink to="/">
          <div class="title-bar">
            <div class="logo-icon">
              <svg
                width="48"
                height="48"
                viewBox="0 0 48 48"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                <rect width="48" height="48" rx="12" fill="#667eea" />
                <path d="M24 12L32 20L24 28L16 20L24 12Z" fill="white" />
                <path d="M24 20L28 24L24 28L20 24L24 20Z" fill="#667eea" />
              </svg>
            </div>
            <div class="title">零码创意</div>
          </div>
        </RouterLink>
      </a-col>

      <!-- 菜单选项 -->
      <a-col flex="auto">
        <a-menu
          v-model:selectedKeys="current"
          mode="horizontal"
          :items="items"
          @click="doMenuClick"
        />
      </a-col>

      <!-- 右侧 导航栏 -->
      <a-col flex="120px">
        <div class="user-login-status">
          <div v-if="loginUserStore.loginUser.id">
            <a-dropdown>
              <ASpace>
                <a-avatar :src="loginUserStore.loginUser.userAvatar" />
                {{ loginUserStore.loginUser.userName ?? '无名' }}
              </ASpace>
              <template #overlay>
                <a-menu>
                  <a-menu-item @click="goToUserCenter">
                    <UserOutlined />
                    个人中心
                  </a-menu-item>
                  <a-menu-item @click="doLogout">
                    <LogoutOutlined />
                    退出登录
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </div>
          <div v-else>
            <a-button type="primary" href="/user/login">登录</a-button>
          </div>
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts" setup>
import { h, ref, computed, onMounted } from 'vue'
import { HomeOutlined, LogoutOutlined, UserOutlined } from '@ant-design/icons-vue'
import { MenuProps, message } from 'ant-design-vue'
import { userLogout } from '@/api/userController.ts'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { useRouter } from 'vue-router'
const router = useRouter()
const loginUserStore = useLoginUserStore()
onMounted(() => {
  loginUserStore.fetchLoginUser()
})
// 跳转到个人中心
const goToUserCenter = () => {
  router.push('/user/center')
}

// 用户注销
const doLogout = async () => {
  const res = await userLogout()
  if (res.data.code === 0) {
    loginUserStore.setLoginUser({
      userName: '未登录',
    })
    message.success('退出登录成功')
    await router.push('/user/login')
  } else {
    message.error('退出登录失败，' + res.data.message)
  }
}

import checkAccess from '@/access/checkAccess.ts'

/**
 * 将路由项转换为菜单项
 * @param item 路由项
 * @returns 菜单项
 */
const menuToRouteItem = (item: any) => {
  // 判断是否为首页
  const isHome = item.path === '/'
  return {
    // 菜单项的唯一标识
    key: item.path,
    // 菜单项显示的文本
    label: item.name,
    // 菜单项的标题
    title: item.name,
    // 仅首页显示图标
    icon: isHome ? h(item.meta?.icon ?? HomeOutlined) : undefined,
  }
}

/**
 * 计算属性，根据权限过滤路由并转换为菜单项
 */
const items = computed(() => {
  return (
    router
      .getRoutes()
      // 过滤掉设置了隐藏的路由项
      .filter((item) => !item.meta?.hideInMenu)
      // 根据用户权限过滤
      .filter((item) => checkAccess(loginUserStore.loginUser, item.meta?.access as string))
      // 将路由项转换为菜单项
      .map(menuToRouteItem)
      .reverse()
  ) // 反转
})

// 响应式存储最终的菜单项
const menus = ref<MenuProps['items']>(items.value)

// 路由跳转事件
const doMenuClick = ({ key }: { key: string }) => {
  router.push({
    path: key,
  })
}

// 当前选中菜单
const current = ref<string[]>([])
// 监听路由变化，更新当前选中菜单
router.afterEach((to, from, next) => {
  current.value = [to.path]
})
</script>

<style scoped>
.title-bar {
  display: flex;
  align-items: center;
}

.title {
  color: black;
  font-size: 18px;
  margin-left: 16px;
}

.logo-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
}

.logo {
  height: 48px;
}
</style>
